<?php
function trim_str($str)
{
    return str_replace('>', '&gt;', str_replace('<', '&lt;', $str));
}

function resize_image($image,$w,$h,$file=false)
{
    $info=getimagesize($image);
    $ow=$info[0];
    $oh=$info[1];
    $mime=$info['mime'];
    $mime=explode('/',$mime);
    $type=$mime[1];
    if($type=='vnd.wap.wbmp'){$type='xbmp';}
    $createfunc='imagecreatefrom'.$type;
    $imagefunc='image'.$type;
    if(!function_exists($createfunc) || !function_exists($imagefunc))
    {
        die("Not support the file format");
    }
    $op=$ow/$oh;
    $p=$w/$h;
    if($p>=$op)
    {
        $w=$op*$h;
    }else{
        $h=$w/$op;
    }
    $thumb = imagecreatetruecolor($w, $h);
    $source = $createfunc($image);
    imagesavealpha($source,true);
    imagealphablending($thumb,false);
    imagesavealpha($thumb,true);
    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $w, $h, $ow, $oh);
    if($file)
    {
        $imagefunc($thumb,$file);
    }
    imagedestroy($source);
    imagedestroy($thumb);
}

function fetch_image($url,$basedir="", $filename="") 
{
    if($url=="") 
    {
        return false;
    }

    if($filename=="") 
    {
        $ext=strrchr($url,".");
        if($ext!=".gif" && $ext!=".jpg" && $ext!=".png") 
        {
            return false;
        }
        $filename = date("YmdHis").$ext;
        if($basedir)
        {
            $filename = "$basedir/$filename";
        }
    }

    ob_start();
    readfile($url);
    $img = ob_get_contents();
    ob_end_clean();
    $size = strlen($img);
    

    $fp2=@fopen($filename, "a");
    fwrite($fp2,$img);
    fclose($fp2);

    return $filename;
}

function fetch_and_resize_img($url, $width, $height, $basedir)
{
    echo $basedir;
    $image_file = fetch_image($url, $basedir);
    $result = resize_image($image_file, $width, $height, $image_file);
    return $image_file;
}

# ut lines:following UT passed
# $url = "http://localhost/test/002.jpg";
# $result = fetch_and_resize_img($url, 200, 200, '/var/www/tianyi/static/article_logo');

?>
